package cn.jinjimi.app.search;

import cn.jinjimi.app.custom.entity.Custom;
import cn.jinjimi.app.custom.manager.CustomsManager;

import java.util.List;
import java.util.regex.Pattern;

/**
 * 客户查询
 * <p/>
 * Created by jinsen on 15/12/7.
 */
public class CustomerProvider extends BaseProvider {

    List<Custom> mCustomList;
    List<Custom> mTargetCustomList;

    int mCustomCount = 0;

    public CustomerProvider(SearchResultListener listener) {
        super(listener);
    }

    public void setCustoms(List<Custom> customs) {
        mTargetCustomList = customs;
    }

    public CustomerProvider(SearchResultListener listener, int pageCount) {
        super(listener, pageCount);
    }

    @Override
    public int doQuery(String key, int startIndex) {
        if (mCancelQuery)
            return QUERY_STATE_CANCEL;

        if (mCustomList == null || startIndex == 0) {
            mCustomList = mTargetCustomList == null ? CustomsManager.getInstance().getCustomsList() : mTargetCustomList;
            mCustomCount = mCustomList.size();
            if (mCancelQuery)
                return QUERY_STATE_CANCEL;
        }

        if (mCustomList == null)
            return QUERY_STATE_FAIL;

        if (mCustomList.isEmpty())
            return QUERY_STATE_OK;

        key = key.toUpperCase();

        int keyWordLen = key.length();

        for (int i = startIndex; i < mCustomCount; i++) {
            if (STOP_QUERY)
                return QUERY_STATE_OK;

            Custom custom = mCustomList.get(i);

            String name = custom.name.toUpperCase();
            int index = name.indexOf(key);
            if (index > -1) {
                mHasNextPager = i < mCustomCount - 1;//是否还有下一页
                CustomSearchRecord record = new CustomSearchRecord();
                record.index = index;
                record.length = keyWordLen;
                record.custom = custom;
                addResult(record);
                continue;
            }

            toCompareChineseNamePinyin(custom, key, i);

        }
        mHasNextPager = false;
        addResult(null);

        return QUERY_STATE_OK;
    }

    Pattern mPatterm = Pattern.compile("^[A-Z]+$");

    private void toCompareChineseNamePinyin(Custom custom, String key, int position) {

    }


}